package com.bida.service.impl;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bida.constant.StatusConstant;
import com.bida.context.BaseContext;
import com.bida.domain.dto.SetmealDTO;
import com.bida.domain.dto.SetmealPageQueryDTO;
import com.bida.domain.po.Dish;
import com.bida.domain.po.Setmeal;
import com.bida.domain.po.SetmealDish;
import com.bida.domain.vo.DishItemVO;
import com.bida.domain.vo.SetmealVO;
import com.bida.exception.BaseException;
import com.bida.mapper.SetmealDishMapper;
import com.bida.mapper.SetmealMapper;
import com.bida.result.PageResult;
import com.bida.result.Result;
import com.bida.service.IDishService;
import com.bida.service.ISetmealDishService;
import com.bida.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.bida.constant.MessageConstant.*;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-09-06
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private ISetmealDishService setmealDishService;

    @Autowired
    private IDishService dishService;

    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 分页查询 套餐
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public Result<PageResult> pageGetSetmeal(SetmealPageQueryDTO setmealPageQueryDTO) {
     int page = setmealPageQueryDTO.getPage();
     int pageSize = setmealPageQueryDTO.getPageSize();
     String name = setmealPageQueryDTO.getName();
     Integer categoryId = setmealPageQueryDTO.getCategoryId();
     Integer status = setmealPageQueryDTO.getStatus();

        IPage<Setmeal> nowPage = new Page<>(page, pageSize);
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        if (name != null){
            queryWrapper.like("name",name);
        }
        if (categoryId != null){
            queryWrapper.eq("category_id",categoryId);
        }
        if (status != null){
            queryWrapper.eq("status",status);
        }
        IPage<Setmeal> setmealIPage = this.page(nowPage, queryWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(setmealIPage.getTotal());
        pageResult.setRecords(setmealIPage.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 新增套餐
     * @param setmealDTO
     * @return
     */
    @Override
    public Result saveNewSetmeal(SetmealDTO setmealDTO) {
         // 获取当前登录用户id
         Long userId = BaseContext.getCurrentId();

//         Long id = setmealDTO.getId();
         Long categoryId = setmealDTO.getCategoryId();
         String name = setmealDTO.getName();
         BigDecimal price = setmealDTO.getPrice();
         Integer status = setmealDTO.getStatus();
         String description = setmealDTO.getDescription();
         String image = setmealDTO.getImage();
         List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

         // 准备容器
        Setmeal setmeal = new Setmeal();
        SetmealDish setmealDish = new SetmealDish();

        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(userId);
        setmeal.setUpdateUser(userId);
        // 保存套餐
        this.save(setmeal);
        // 获取该套餐id
        Long setmealNowId = this.lambdaQuery()
                .eq(Setmeal::getName, name)
                .eq(Setmeal::getCategoryId, categoryId)
                .one().getId();

        for (SetmealDish dish : setmealDishes) {
            dish.setSetmealId(setmealNowId);
            setmealDishService.save(dish);
        }
        return Result.success();
    }

    /**
     * 套餐起售、停售
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result updateSetmealStatus(Integer status, Long id) {
        // 如果是起售，判断菜品中是否有未起售菜品
        if (status.equals(StatusConstant.ENABLE)){
            List<SetmealDish> list = setmealDishService.lambdaQuery()
                    .eq(SetmealDish::getSetmealId, id)
                    .list();
            for (SetmealDish setmealDish : list) {
                Dish one = dishService.lambdaQuery()
                        .eq(Dish::getId, setmealDish.getDishId())
                        .one();
                if (one.getStatus().equals(StatusConstant.DISABLE)){
                    throw new BaseException(SETMEAL_ENABLE_FAILED);
                }
            }
        }
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        this.lambdaUpdate()
                .eq(Setmeal::getId, id)
                .set(Setmeal::getStatus, status)
                .set(Setmeal::getUpdateUser, userId)
                .set(Setmeal::getUpdateTime, LocalDateTime.now())
                .update();
        return Result.success();
    }

    /**
     * 修改套餐
     * @param setmealDTO
     * @return
     */
    @Override
    public Result updateSetmealInfo(SetmealDTO setmealDTO) {
        // 判断起售中的套餐，禁止修改
        Long id = setmealDTO.getId();
        Setmeal byId = this.getById(id);
        if (byId.getStatus().equals(StatusConstant.ENABLE)){
            throw new BaseException(SETMEAL_ON_UPDATE);
        }
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(userId);
        this.updateById(setmeal);

        // 清空原有套餐关联
        List<SetmealDish> ids = setmealDishService.lambdaQuery()
                .eq(SetmealDish::getSetmealId, id)
                .list();
        for (SetmealDish setmealDish : ids) {
            setmealDishService.removeById(setmealDish.getId());
        }
        // 重新塞
        for (SetmealDish setmealDish : setmealDTO.getSetmealDishes()) {
            setmealDish.setSetmealId(id);
            setmealDishService.save(setmealDish);
        }
        return Result.success();
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Result<SetmealVO> getSetmealInfoById(Long id) {
        Setmeal setmeal = this.getById(id);
        List<SetmealDish> list = setmealDishService.lambdaQuery()
                .eq(SetmealDish::getSetmealId, id)
                .list();
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(list);
        return Result.success(setmealVO);
    }

    /**
     * 批量删除套餐
     * @param ids
     * @return
     */
    @Override
    public Result deleteSetmealByIds(List<Long> ids) {
        if (ids.isEmpty()){
            throw new BaseException(SETMEAL_IDS_NULL);
        }
        for (Long id : ids) {
            Setmeal byId = this.getById(id);
            if (byId.getStatus().equals(StatusConstant.ENABLE)){
                throw new BaseException(SETMEAL_ON_SALE);
            }
        }
        for (Long id : ids) {
            this.removeById(id);
            setmealDishService.lambdaUpdate()
                    .eq(SetmealDish::getSetmealId, id)
                    .remove();
        }
        return Result.success();
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    @Override
    public List<Setmeal> getAllList(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.getAllList(setmeal);
        return list;
    }


    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
